﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;

namespace ConsoleService.Cache
{
    public class MemoryCacheHelper
    {
        public static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());


        /// <summary>
        /// 验证缓存是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            object cached;
            return _cache.TryGetValue(key, out cached);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(string key)
        {
            return _cache.Get(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T">泛型(返回的结果类型)</typeparam>
        /// <param name="key">缓存key</param>
        /// <returns></returns>
        public static T Get<T>(string key) where T : new()
        {
            try
            {
                if (!string.IsNullOrEmpty(key))
                {
                    return JsonConvert.DeserializeObject<T>(_cache.Get(key).ToString());
                }
                else
                {
                    return default(T);
                }
            }
            catch
            {
                return default(T);
            }
        }


        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiresSliding">滑动过期时长（如果在过期时间内有操作，则以当前时间点延长过期时间）</param>
        /// <param name="expiressAbsoulte">绝对过期时长</param>
        /// <returns></returns>
        public static bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            _cache.Set(key, value,
                    new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(expiresSliding)
                    .SetAbsoluteExpiration(expiressAbsoulte)
                    );

            return Exists(key);
        }


        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="absoluteExpiration">绝对过期时长</param>
        /// <returns></returns>
        public static bool Add(string key, object value, DateTimeOffset absoluteExpiration)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            _cache.Set(key, value, absoluteExpiration);

            return Exists(key);
        }


        public static T GetOrSet<T>(string key, DateTimeOffset cacheTime, Func<T> acquire)
        {
            if (Exists(key))
            {
                return _cache.Get<T>(key);
            }
            else
            {
                var result = acquire();
                if (result != null)
                    Add(key, result, cacheTime);
                return result;
            }
        }

        /// <summary>
        /// 移出缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            _cache.Remove(key);
        }

    }
}
